<?php
class couponModel extends RPHP_Model
{

    protected $_auth = null;

    //检查权限
    public function checkPriv($pv, $return = true)
    {
        $auth = $this->auth->CheckPriv($pv, $return);
        if ($return) {
            $this->_auth = $auth;
        }

        return $auth;
    }

    public function getAllMember($para)
    {
        $where = " `stat`=1 ";
        if ($para['info']) {
       
            $where .= " AND (`realname` LIKE '%" . $para['info'] . "%')";
            $sql = "SELECT `uid`,`realname` FROM {$this->_prefix['primary']}member_wechat WHERE " . $where;
            return $this->sql($sql);
        }
    
    }
    //获取会员列表
    public function getCouponList($para, $page = 1, $pagesize = 20)
    {
        $where = " `status`<3 ";
        if ($para) {

            if ($para['stat'] > 0) {
                $where .= " AND `stat`=" . $para['stat'];
            }
            if (isset($para['type'])) {
                $where .= " AND `type`=" . $para['type'];
                
            }

            if ($para['pid'] > 0) {
                $where .= " AND `pid`=" . $para['pid'];
            }

            if (isset($para['member_level'])) {
                $where .= " AND `member_level`=" . $para['member_level'];
            }
            if (isset($para['store_id'])) {
                $where .= " AND `store_id`=" . $para['store_id'];
            }

            if ($para['keyword'] != '') {
                      
                $sql = "SELECT `uid` FROM {$this->_prefix['primary']}member_wechat WHERE `realname` LIKE '%" . $para['keyword'] . "%'" ;
                $stores = $this->sql($sql);
                if($stores){
                   
                    foreach($stores as $v){
                        
                        if($v['uid']){
                            
                            $top_uids[$v['uid']] = $v['uid'];
                        }
                    }
                    
                    if($top_uids){
                        
                        $where .= " AND `uid` IN (".implode(",",$top_uids).")";
                    }
                }else{
                    $where .= " AND `uid`=0";
                    
                }

            }

        }
       

        $sql = "SELECT COUNT(`dis_id`) AS `cnt` FROM {$this->_prefix['primary']}discount_data  WHERE " . $where;
        $cnt = $this->db->getone($sql);
        if ($cnt > 0) {

            $start = ($page - 1) * $pagesize;
            //默认排序
            $orderby = "`dis_id` DESC";

            $sql = "SELECT * FROM {$this->_prefix['primary']}discount_data WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
            $rs  = $this->sql($sql);

            if ($rs) {
                 foreach($rs as $v){
                     if($v['uid']){
                        $uids[$v['uid']] = $v['uid'];
                    
                     }
                 
                 }
                 
                 if ($uids) {
                     $sql          = "SELECT `uid`,`nickname`,`realname` FROM {$this->_prefix['primary']}member_wechat WHERE `uid` IN (" . implode(",", array_unique($uids)) . ")";
                     $members = $this->sql($sql);
                     
                     if($members){
                         
                         foreach($members as $v){
                             $users[$v['uid']] = $v;
                              
                         }
                     }
                 }
            }

            return array(
                'page'    => $page,
                'maxpage' => ceil($cnt / $pagesize),
                'count'   => $cnt,
                'data'    => $rs,
                'para'    => $para,
                'users'    => $users,
            );

        }
    }

    public function getCouponUseDetail($para, $page = 1, $pagesize = 20)
    {
        $dis_id = intval($_GET['dis_id']);
        if($dis_id){
            $where = "`dis_id`=".$dis_id;
            if ($para['keyword'] != '') {
                      
                $sql = "SELECT `uid` FROM {$this->_prefix['primary']}member_wechat WHERE `realname` LIKE '%" . $para['keyword'] . "%'" ;
                $stores = $this->sql($sql);
                if($stores){
                   
                    foreach($stores as $v){
                        
                        if($v['uid']){
                            
                            $top_uids[$v['uid']] = $v['uid'];
                        }
                    }
                    
                    if($top_uids){
                        
                        $where .= " AND `uid` IN (".implode(",",$top_uids).")";
                    }
                }else{
                    $where .= " AND `uid`=0";
                    
                }

            }
          
            $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}discount_coupon  WHERE " . $where;
            $cnt = $this->db->getone($sql);
            if ($cnt > 0) {
            
                $start = ($page - 1) * $pagesize;
                //默认排序
                $orderby = "`create_time` DESC";
            
                $sql = "SELECT * FROM {$this->_prefix['primary']}discount_coupon WHERE " . $where . " ORDER BY " . $orderby . " LIMIT " . $start . "," . $pagesize;
                $rs  = $this->sql($sql);
                foreach($rs as $v){
                     if($v['uid']){
                        $uids[$v['uid']] = $v['uid'];
                    
                     }
                 
                 }
                 
                 if ($uids) {
                     $sql          = "SELECT `uid`,`nickname`,`realname` FROM {$this->_prefix['primary']}member_wechat WHERE `uid` IN (" . implode(",", array_unique($uids)) . ")";
                     $members = $this->sql($sql);
                      
                     if($members){
                          
                         foreach($members as $v){
                             $users[$v['uid']] = $v['realname'];
                 
                         }
                     }
                 }
                return array(
                    'page'    => $page,
                    'maxpage' => ceil($cnt / $pagesize),
                    'count'   => $cnt,
                    'data'    => $rs,
                    'para'    => $para,
                    'users'    => $users,
                );
                
            }
        }
        
    }
    // 获取单个优惠券
    public function getSingleCoupon($dis_id)
    {
        $sql = "SELECT * FROM {$this->_prefix['primary']}discount_data WHERE `dis_id`=" . $dis_id . " AND `status`<3";
        return $this->db->getrow($sql);
    }

    // 获取门店
    public function getStore($storeid = 0)
    {
        if ($storeid > 0) {
            $where = " AND `store_id`=" . intval($storeid);
        }

        $sql = "SELECT * FROM {$this->_prefix['primary']}store WHERE  `stat`<3 " . $where . " ORDER BY `store_id` ASC";
        if ($storeid > 0) {
            $data = $this->db->getrow($sql);
        } else {
            $data = $this->sql($sql);
        }

        return $data;
    }

    // 新增优惠券
    public function addCoupon($da)
    {
        $code = 900;

       
        $money        = number_format($da['money'], 2, ".", "");
        $min_money    = number_format($da['min_money'], 2, ".", "");
        $max_num      = intval($da['max_num']);
        $expire_month = intval($da['expire_month']);
        $status = intval($da['status']);
        $use_get_num = intval($da['use_get_num']);
        $goods_ids = '';
        if($da['goods_ids']){
            $goods_ids = $this->unique($da['goods_ids']);
            
        }
        
        
        if ($money > 0 && $max_num > 0 && $expire_month > 0 && $use_get_num>0) {
            $sql = "INSERT INTO {$this->_prefix['primary']}discount_data (`money`,`min_money`,`max_num`,`status`,`goods_ids`,`use_get_num`,`expire_month`,`create_time`,`create_aid`) VALUES (" . $money . "," . $min_money . "," . $max_num . "," . $status . ",'" . $goods_ids . "'," . $use_get_num . "," . $expire_month . "," . $_SERVER['REQUEST_TIME'] . "," . $this->_auth['staffid'] . ")";
            $rcs = $this->sql($sql);
            if ($rcs > 0) {
                $code = 200;
            } else {
                $code = 403;
            }
        }

        return $code;
    }

    public function unique($str)
    {  
        $arr = explode(',', $str);  
        $arr = array_unique($arr);//内置数组去重算法  
        $data = implode(',', $arr);  
        $data = trim($data,',');//trim — 去除字符串首尾处的空白字符（或者其他字符）,假如不使用，后面会多个逗号  
        return $data;//返回值，返回到函数外部  
    } 

    // 编辑优惠券
    public function editCoupon($da)
    {
        $code = 900;

        $dis_id       = intval($da['dis_id']);
        $money        = number_format($da['money'], 2, ".", "");
        $min_money    = number_format($da['min_money'], 2, ".", "");
        $max_num      = intval($da['max_num']);
        $expire_month = intval($da['expire_month']);
        $status       = intval($da['status']);
        
        $use_get_num = intval($da['use_get_num']);
        $goods_ids = '';
        if($da['goods_ids']){
            $goods_ids = $this->unique($da['goods_ids']);
        
        }
        if ($status < 1 || $status > 3) {
            $status = 1;
        }

        if ($money > 0 && $max_num > 0 && $expire_month > 0 && $dis_id > 0) {

            $data = $this->getSingleCoupon($dis_id);
            if ($data) {
                $sql = "UPDATE {$this->_prefix['primary']}discount_data SET `money`=" . $money . ",`min_money`=" . $min_money . ",`max_num`=" . $max_num . ",`expire_month`=" . $expire_month . ",`status`=" . $status . ",`goods_ids`='" . $goods_ids . "',`use_get_num`=" . $use_get_num . ",`last_aid`=" . $this->_auth['staffid'] . ",`last_edit`=" . $_SERVER['REQUEST_TIME'] . " WHERE `dis_id`=" . $data['dis_id'];

                $rcs = $this->sql($sql);
                if ($rcs > 0) {
                    $code = 200;
                } else {
                    $code = 403;
                }
            } else {
                $code = 404;
            }

        }

        return $code;
    }
    //删除代金券
    public function delVoucher($dis_id)
    {
        $dis_id = intval($dis_id);
        $arr['code']=900;
        $arr['msg']="删除失败，请重试";
        if($dis_id){
            
            $sql = "DELETE FROM {$this->_prefix['primary']}discount_data WHERE `dis_id`=" . $dis_id . "   LIMIT 1";
            $res = $this->sql($sql);
            if($res){
                $arr['code']=200;
                $arr['msg']="删除成功";
                
            }
        }else{
            $arr['code']=901;
        }
        return $arr;
    }
    //删除用户优惠券
    public function delDiscountCoupon($coupon_id)
    {
       
        $coupon_id = intval($coupon_id);
        $arr['code']=900;
        $arr['msg']="删除失败，请重试";
        if($coupon_id){
            
            $sql = "DELETE FROM {$this->_prefix['primary']}discount_coupon WHERE `coupon_id`=" . $coupon_id . "   LIMIT 1";
            $res = $this->sql($sql);
            if($res){
                $arr['code']=200;
                $arr['msg']="删除成功";
                
            }
        }else{
            $arr['code']=901;
        }
        return $arr;
    }
    
    //发放代金券
    public function sendVoucher($da)
    {
        $code =900;
        $money        = number_format($da['money'], 2, ".", "");
        $uid          = explode('-', $da['uid'])[0];
      
        if(is_numeric($uid) && $uid>0){
            $sql  = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `uid`=" .$uid . " AND `stat`=1";
            $member = $this->db->getrow($sql);
        
        }
       
        if($money && $member){
          
            $this->db->begin();
            $commit = false;
            
            $sql = "SELECT COUNT(*)  FROM {$this->_prefix['primary']}discount_data WHERE `uid`=".$member['uid'];
            $num = $this->db->getone($sql);
            
            if($num){
                
                //修改
                $sql = "UPDATE {$this->_prefix['primary']}discount_data SET `money`=`money`+".$money.",`last_edit`=" . time() . " WHERE `uid`=" . $member['uid'];
                $dis_id = $this->sql($sql);
            }else{
                $sql = "INSERT INTO {$this->_prefix['primary']}discount_data (`money`,`create_time`,`create_aid`,`uid`,`type`) VALUES (" . $money . "," . $_SERVER['REQUEST_TIME'] . "," . $this->_auth['staffid'] . "," . $uid . ",1)";
                $dis_id = $this->sql($sql);
                
            }
           
            if($dis_id){
               
                    $commit = true;
                    $code = 200;
                
            }
        }
        
        if ($commit) {
            $this->db->commit();
        } else {
            $this->db->rollback();
        }
        
        return $code;
        
    }
    
    //发送优惠券
    public function sendCoupon($da)
    {
        $code =900;
        $uid          = explode('-', $da['uid'])[0];
        $send_num = intval($da['send_num']);
        $id = intval($da['dis_id']);
        if(is_numeric($uid) && $uid>0){
            $sql  = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `uid`=" .$uid . " AND `stat`=1";
            $member = $this->db->getrow($sql);
    
        }
        
        if($member && $id && $send_num>0){
    
            
            $sql = "SELECT *  FROM {$this->_prefix['primary']}discount_data WHERE `type`=0 AND `dis_id`=".$id;
            $coupon = $this->db->getrow($sql);
            //print_r($coupon);die(111);
            if($coupon){
               /*  $sql = "INSERT INTO {$this->_prefix['primary']}discount_coupon (`money`,`create_time`,`uid`,`dis_id`,`type`) VALUES (" . $money . "," . $_SERVER['REQUEST_TIME'] . "," . $uid . "," . $dis_id . ",1)";
                $rcs = $this->sql($sql); */
                
            /*     $sql = "SELECT COUNT(*) AS `cnt` FROM {$this->_prefix['primary']}discount_coupon WHERE `uid`=" . $member['uid']." AND  `dis_id`=".$coupon['dis_id']." AND `type`=0";
                $cnt = $this->db->getone($sql);
                if($cnt >=$coupon['use_get_num']){
                   return "此用户已领取完";
                }
                
                if($coupon['max_num'] <= $coupon['sent_num']){
                    
                    return "优惠券已领完";
                } */
                $this->db->begin();
                $commit = true;
                
                
                for($i=0;$i<$send_num;$i++){
                    
                    if($commit){
                        
                        //添加用户优惠券
                        $couponsql          = "INSERT INTO {$this->_prefix['primary']}discount_coupon (`uid`,`dis_id`,`money`,`min_money`,`create_time`,`expire_time`,`goods_ids`) VALUES ";
                        $coupon_create_time = $_SERVER['REQUEST_TIME'];
                        $coupon_expire_time = strtotime("+".$coupon['expire_month']." months");
                         
                        $couponsql .= "(" . $member['uid'] . "," . $coupon['dis_id'] . "," .$coupon['money'] . "," . $coupon['min_money'] . ",".$coupon_create_time."," . $coupon_expire_time . ",'" . $coupon['goods_ids'] . "')";
                         
                        $rcp = $this->sql($couponsql);
                       
                        if(!$rcp){
                            
                            $commit = false;
                        }
                    
                    }
                }
                
                 if($commit){
                     $commit = false;
                    //修改发放数量
                    $sql = "UPDATE {$this->_prefix['primary']}discount_data SET `sent_num`=sent_num+".$send_num.",`last_edit`=" . time() . " WHERE `dis_id`=" . $coupon['dis_id'];
                    $rcs = $this->sql($sql);
                    if($rcs){
                        
                        $commit = true;
                        $code = 200;
                    }
                } 
    
            }
        }
    
        if ($commit) {
            $code = 200;
            $this->db->commit();
        } else {
            $this->db->rollback();
        }
    
        return $code;
    
    }
    
    

}
